package com.company.genealogy.web.service.impl;

import com.company.genealogy.common.util.SecurityContextUtil;
import com.company.genealogy.web.entity.Spouse;
import com.company.genealogy.web.mapper.SpouseMapper;
import com.company.genealogy.web.service.SpouseService;
import com.company.genealogy.web.vo.SpouseVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 配偶信息服务实现
 */
@Service
public class SpouseServiceImpl implements SpouseService {
    
    @Autowired
    private SpouseMapper spouseMapper;
    
    @Autowired
    private SecurityContextUtil securityContextUtil;
    
    @Override
    public List<SpouseVO> getSpouseList(Integer page, Integer size) {
        // 使用简化的查询方法，避免字符集冲突
        List<Spouse> spouses = spouseMapper.selectAllOrderByCreatedAt();
        
        // 手动分页
        int start = (page - 1) * size;
        int end = Math.min(start + size, spouses.size());
        
        if (start >= spouses.size()) {
            return new ArrayList<>();
        }
        
        return spouses.subList(start, end).stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }
    
    @Override
    public SpouseVO getSpouseById(Long id) {
        if (id == null) return null;
        
        Spouse spouse = spouseMapper.selectById(id);
        return convertToVO(spouse);
    }
    
    @Override
    @Transactional
    public SpouseVO createSpouse(SpouseVO spouseVO) {
        // 权限检查
        if (!securityContextUtil.isAdmin() && !securityContextUtil.isClanLeader()) {
            throw new RuntimeException("无权限创建配偶信息");
        }
        
        Spouse spouse = convertToEntity(spouseVO);
        spouseMapper.insert(spouse);
        
        return convertToVO(spouse);
    }
    
    @Override
    @Transactional
    public SpouseVO updateSpouse(Long id, SpouseVO spouseVO) {
        // 权限检查
        if (!securityContextUtil.isAdmin() && !securityContextUtil.isClanLeader()) {
            throw new RuntimeException("无权限更新配偶信息");
        }
        
        Spouse existingSpouse = spouseMapper.selectById(id);
        if (existingSpouse == null) {
            throw new RuntimeException("配偶信息不存在");
        }
        
        Spouse spouse = convertToEntity(spouseVO);
        spouse.setId(id);
        spouseMapper.updateById(spouse);
        
        return convertToVO(spouse);
    }
    
    @Override
    @Transactional
    public boolean deleteSpouse(Long id) {
        // 权限检查
        if (!securityContextUtil.isAdmin() && !securityContextUtil.isClanLeader()) {
            throw new RuntimeException("无权限删除配偶信息");
        }
        
        Spouse spouse = spouseMapper.selectById(id);
        if (spouse == null) {
            return false;
        }
        
        return spouseMapper.deleteById(id) > 0;
    }
    
    @Override
    public List<SpouseVO> searchSpouseByName(String name) {
        if (name == null || name.trim().isEmpty()) {
            return new ArrayList<>();
        }
        
        List<Spouse> spouses = spouseMapper.searchByName(name.trim());
        return spouses.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }
    
    @Override
    public List<SpouseVO> getSpouseByGender(String gender) {
        if (gender == null || gender.trim().isEmpty()) {
            return new ArrayList<>();
        }
        
        List<Spouse> spouses = spouseMapper.selectByGender(gender.trim());
        return spouses.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }
    
    @Override
    public List<SpouseVO> getSpouseByStatus(String status) {
        if (status == null || status.trim().isEmpty()) {
            return new ArrayList<>();
        }
        
        Integer statusValue = "在世".equals(status) ? 1 : 0;
        List<Spouse> spouses = spouseMapper.selectByStatus(statusValue);
        return spouses.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }
    
    /**
     * 转换为VO
     */
    private SpouseVO convertToVO(Spouse spouse) {
        if (spouse == null) return null;
        SpouseVO vo = new SpouseVO();
        BeanUtils.copyProperties(spouse, vo);
        vo.setStatus(spouse.getStatus() != null ? 
            (spouse.getStatus() == 1 ? "在世" : "已故") : "未知");
        
        // 处理籍贯显示名称 - 暂时使用代码，后续可以通过单独查询获取名称
        vo.setNativeProvinceName(spouse.getNativeProvinceCode());
        vo.setNativeCityName(spouse.getNativeCityCode());
        vo.setNativeCountyName(spouse.getNativeCountyCode());
        vo.setNativeTownName(spouse.getNativeTownCode());
        
        return vo;
    }
    
    /**
     * 转换为实体
     */
    private Spouse convertToEntity(SpouseVO spouseVO) {
        if (spouseVO == null) return null;
        
        Spouse spouse = new Spouse();
        BeanUtils.copyProperties(spouseVO, spouse);
        spouse.setStatus("在世".equals(spouseVO.getStatus()) ? 1 : 0);
        return spouse;
    }
    
    /**
     * 权限检查
     */
    private boolean hasPermission() {
        return securityContextUtil.isAdmin() || securityContextUtil.isClanLeader();
    }
} 